/**
 * 时间修复辅助脚本
 * 用于批量修复页面中的时间显示问题
 */

import { 
  formatLocalDate, 
  formatRelativeTime, 
  getDateStatus,
  isOverdue,
  isToday,
  TimeUtils
} from './timeUtils'

/**
 * 修复任务对象中的时间字段
 */
export const fixTaskTimeFields = (task: any) => {
  if (!task) return task
  
  return {
    ...task,
    // 统一时间字段处理
    dueDate: task.dueDate ? new Date(task.dueDate) : undefined,
    createdAt: task.createdAt ? new Date(task.createdAt) : new Date(),
    updatedAt: task.updatedAt ? new Date(task.updatedAt) : new Date(),
    
    // 保持其他字段不变
    priority: task.priority as 'P0' | 'P1' | 'P2' | 'P3',
  }
}

/**
 * 修复任务列表中的时间字段
 */
export const fixTaskListTimeFields = (tasks: any[]) => {
  return tasks.map(fixTaskTimeFields)
}

/**
 * 统一的时间分组逻辑
 */
export const groupTasksByTime = (tasks: any[]) => {
  const processedTasks = fixTaskListTimeFields(tasks)
  
  return {
    overdue: processedTasks.filter(task => {
      if (!task.dueDate || task.completed) return false
      return isOverdue(task.dueDate)
    }),
    today: processedTasks.filter(task => {
      if (!task.dueDate || task.completed) return false
      return isToday(task.dueDate)
    }),
    upcoming: processedTasks.filter(task => {
      if (!task.dueDate || task.completed) return false
      const status = getDateStatus(task.dueDate)
      return status === 'upcoming' || status === 'tomorrow'
    }),
    noDate: processedTasks.filter(task => !task.dueDate && !task.completed)
  }
}

/**
 * 统一的时间显示格式化
 */
export const formatTaskTime = (task: any) => {
  if (!task.dueDate) return '无截止时间'
  
  const date = new Date(task.dueDate)
  if (isNaN(date.getTime())) return '无效时间'
  
  // 如果有具体时间
  if (task.dueTime) {
    return `${formatLocalDate(date)} ${task.dueTime}`
  }
  
  // 只有日期
  return formatLocalDate(date)
}

/**
 * 统一的相对时间显示
 */
export const formatTaskRelativeTime = (task: any) => {
  if (!task.dueDate) return ''
  
  return formatRelativeTime(task.dueDate)
}

/**
 * 统一的时间状态判断
 */
export const getTaskTimeStatus = (task: any) => {
  if (!task.dueDate) return { status: 'none', text: '', style: '' }
  
  const date = TimeUtils.parseDate(task.dueDate)
  if (!date) return { status: 'invalid', text: '无效时间', style: 'text-red-500' }
  
  if (TimeUtils.isOverdue(date)) {
    const days = TimeUtils.getDaysDiff(new Date(), date)
    return {
      status: 'overdue',
      text: `已过期${Math.abs(days)}天`,
      style: 'text-red-600 bg-red-50'
    }
  }
  
  if (TimeUtils.isToday(date)) {
    return {
      status: 'today',
      text: '今天到期',
      style: 'text-orange-600 bg-orange-50'
    }
  }
  
  if (TimeUtils.isTomorrow(date)) {
    return {
      status: 'tomorrow',
      text: '明天到期',
      style: 'text-blue-700 bg-blue-100 border-blue-200'
    }
  }
  
  const days = TimeUtils.getDaysDiff(date, new Date())
  return {
    status: 'future',
    text: `${days}天后到期`,
    style: 'text-blue-700 bg-blue-100 border-blue-200'
  }
}

/**
 * 快速日期设置辅助函数
 */
export const getQuickDateOptions = () => {
  const today = TimeUtils.formatDate(new Date(), 'YYYY-MM-DD')
  const tomorrow = TimeUtils.formatDate(TimeUtils.addDays(new Date(), 1), 'YYYY-MM-DD')
  const nextWeek = TimeUtils.formatDate(TimeUtils.addDays(new Date(), 7), 'YYYY-MM-DD')
  
  return {
    today,
    tomorrow,
    nextWeek,
    options: [
      { key: 'today', label: '今天', value: today },
      { key: 'tomorrow', label: '明天', value: tomorrow },
      { key: 'week', label: '下周', value: nextWeek }
    ]
  }
}

/**
 * 智能时间解析（本地化版本）
 */
export const parseSmartTime = (text: string) => {
  const result = {
    dueDate: null as string | null,
    dueTime: '' as string,
    priority: 'P2' as 'P0' | 'P1' | 'P2' | 'P3',
  }
  
  // 使用统一的时间工具进行解析
  const today = TimeUtils.formatDate(new Date(), 'YYYY-MM-DD')
  
  // 时间解析
  const timeMatch = text.match(/(上午|下午|晚上|早上|中午)?\s*(\d{1,2})(点|时|:)\s*(半|(\d{1,2})(分?)|(\d{2}))?/)
  if (timeMatch) {
    const timePrefix = timeMatch[1]
    let hour = parseInt(timeMatch[2])
    let minute = 0
    
    if (timeMatch[4] === '半') {
      minute = 30
    } else if (timeMatch[5]) {
      minute = parseInt(timeMatch[5])
    } else if (timeMatch[7]) {
      minute = parseInt(timeMatch[7])
    }
    
    if (timePrefix === '下午' || timePrefix === '晚上') {
      if (hour < 12) hour += 12
    } else if (timePrefix === '上午' && hour === 12) {
      hour = 0
    }
    
    if (!timePrefix && hour < 8 && hour !== 0) {
      hour += 12
    }
    
    result.dueTime = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
  }
  
  // 日期解析
  if (/(今天|现在)/.test(text) || (timeMatch && !/(明天|后天|下周)/.test(text))) {
    result.dueDate = today
  } else if (/明天/.test(text)) {
    result.dueDate = TimeUtils.formatDate(TimeUtils.addDays(new Date(), 1), 'YYYY-MM-DD')
  } else if (/后天/.test(text)) {
    result.dueDate = TimeUtils.formatDate(TimeUtils.addDays(new Date(), 2), 'YYYY-MM-DD')
  } else if (/大后天/.test(text)) {
    result.dueDate = TimeUtils.formatDate(TimeUtils.addDays(new Date(), 3), 'YYYY-MM-DD')
  }
  
  // 优先级解析
  if (/(紧急|重要|优先)/.test(text)) {
    result.priority = 'P0'
  } else if (/(一般|普通)/.test(text)) {
    result.priority = 'P2'
  }
  
  return result
}

export default {
  fixTaskTimeFields,
  fixTaskListTimeFields,
  groupTasksByTime,
  formatTaskTime,
  formatTaskRelativeTime,
  getTaskTimeStatus,
  getQuickDateOptions,
  parseSmartTime
}